class Database {
    constructor() {
        this.dbName = 'webBatchCreateDB';
        this.version = 1;
        this.db = null;
        this.initPromise = this.init();
    }

    async init() {
        return new Promise((resolve, reject) => {
            const request = indexedDB.open(this.dbName, this.version);

            request.onerror = () => {
                console.error('数据库打开失败');
                reject(request.error);
            };

            request.onsuccess = () => {
                this.db = request.result;
                console.log('数据库打开成功');
                resolve();
            };

            request.onupgradeneeded = (event) => {
                const db = event.target.result;

                // 创建模板存储
                if (!db.objectStoreNames.contains('templates')) {
                    const templateStore = db.createObjectStore('templates', { keyPath: 'id', autoIncrement: true });
                    templateStore.createIndex('name', 'name', { unique: false });
                }

                // 创建数据存储
                if (!db.objectStoreNames.contains('data')) {
                    const dataStore = db.createObjectStore('data', { keyPath: 'id', autoIncrement: true });
                    dataStore.createIndex('templateId', 'templateId', { unique: false });
                    dataStore.createIndex('createdAt', 'createdAt', { unique: false });
                }
            };
        });
    }

    async ensureConnection() {
        if (!this.db) {
            await this.initPromise;
        }
        return this.db;
    }

    async saveTemplate(template) {
        const db = await this.ensureConnection();
        return new Promise((resolve, reject) => {
            const transaction = db.transaction(['templates'], 'readwrite');
            const store = transaction.objectStore('templates');
            const request = store.add(template);

            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(request.error);
        });
    }

    async updateTemplate(template) {
        const db = await this.ensureConnection();
        return new Promise((resolve, reject) => {
            const transaction = db.transaction(['templates'], 'readwrite');
            const store = transaction.objectStore('templates');
            const request = store.put(template);

            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(request.error);
        });
    }

    async getTemplate(id) {
        const db = await this.ensureConnection();
        return new Promise((resolve, reject) => {
            const transaction = db.transaction(['templates'], 'readonly');
            const store = transaction.objectStore('templates');
            const request = store.get(id);

            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(request.error);
        });
    }

    async getTemplates() {
        const db = await this.ensureConnection();
        return new Promise((resolve, reject) => {
            const transaction = db.transaction(['templates'], 'readonly');
            const store = transaction.objectStore('templates');
            const request = store.getAll();

            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(request.error);
        });
    }

    async deleteTemplate(id) {
        const db = await this.ensureConnection();
        return new Promise((resolve, reject) => {
            const transaction = db.transaction(['templates'], 'readwrite');
            const store = transaction.objectStore('templates');
            const request = store.delete(id);

            request.onsuccess = () => resolve();
            request.onerror = () => reject(request.error);
        });
    }

    async saveData(data) {
        const db = await this.ensureConnection();
        return new Promise((resolve, reject) => {
            const transaction = db.transaction(['data'], 'readwrite');
            const store = transaction.objectStore('data');
            const request = store.add(data);

            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(request.error);
        });
    }

    async getDataByTemplate(templateId) {
        const db = await this.ensureConnection();
        return new Promise((resolve, reject) => {
            const transaction = db.transaction(['data'], 'readonly');
            const store = transaction.objectStore('data');
            const index = store.index('templateId');
            const request = index.getAll(templateId);

            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(request.error);
        });
    }

    async getAllData() {
        const db = await this.ensureConnection();
        return new Promise((resolve, reject) => {
            const transaction = db.transaction(['data'], 'readonly');
            const store = transaction.objectStore('data');
            const request = store.getAll();

            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(request.error);
        });
    }

    async clearAllData() {
        const db = await this.ensureConnection();
        return new Promise((resolve, reject) => {
            const transaction = db.transaction(['templates', 'data'], 'readwrite');
            const templatesStore = transaction.objectStore('templates');
            const dataStore = transaction.objectStore('data');
            
            const templatesRequest = templatesStore.clear();
            const dataRequest = dataStore.clear();
            
            let completed = 0;
            const total = 2;
            
            const checkCompletion = () => {
                completed++;
                if (completed === total) {
                    resolve();
                }
            };
            
            templatesRequest.onsuccess = checkCompletion;
            dataRequest.onsuccess = checkCompletion;
            
            templatesRequest.onerror = () => reject(templatesRequest.error);
            dataRequest.onerror = () => reject(dataRequest.error);
        });
    }
}

// 创建数据库实例
const db = new Database(); 